<template>
  <el-card>
    <div slot="header">
      <span>指定成员管理</span>
      <span class="desc-text ml10">将成员加入权限组，授权他们填写或管理数据</span>
    </div>
    <url-operate class="ml20" :link-url="createDataLink" />
    <el-divider />
    <div class="publish-content">
      <el-button type="primary" @click="crateAuthGroupHandle">
        新建权限组
      </el-button>
      <el-divider />
      <div v-if="authGroupList.length!==0" class="auth-group-list">
        <div v-for="(group) in authGroupList" :key="`group${group.id}`" class="auth-group-item">
          <el-row align="middle" justify="center" type="flex">
            <el-col :span="20">
              {{ group.name }}
            </el-col>
            <el-col :span="4">
              <el-button type="text" @click="updateAuthGroupHandle(group.id)">
                编辑
              </el-button>
              <el-button type="text" @click="copyAuthGroupHandle(group.id)">
                复制
              </el-button>
              <el-button class="text-danger" type="text" @click="deleteAuthGroupHandle(group.id)">
                删除
              </el-button>
            </el-col>
          </el-row>
          <p class="desc-text">
            {{ group.description }}
          </p>

          <div v-if="group.authObjs">
            <span v-for="user in group.authObjs.userList" :key="`user${user.id}`" class="auth-obj-tag">
              <el-tag>{{ user.userName }}</el-tag>
            </span>
            <span v-for="role in group.authObjs.roleList" :key="`role${role.id}`" class="auth-obj-tag">
              <el-tag type="success">{{ role.roleName }}</el-tag>
            </span>
            <span v-for="dept in group.authObjs.deptList" :key="`role${dept.id}`" class="auth-obj-tag">
              <el-tag type="info">{{ dept.label }}</el-tag>
            </span>
          </div>
          <el-button type="text" @click="authGroupToUserHandle(group)">
            分配权限
          </el-button>
          <el-divider />
        </div>
      </div>
    </div>
    <auth-group ref="authGroup" :form-key="formKey" />
    <user-choose-table ref="userChooseTable"
                       @submit="(val)=>submitChooseHandle('user',val)"
    />
    <role-choose-table ref="roleChooseTable"
                       @submit="(val)=>submitChooseHandle('role',val)"
    />
    <dept-choose-tree ref="deptChooseTree"
                      @submit="(val)=>submitChooseHandle('dept',val)"
    />
    <el-dialog
      :visible.sync="authDialogVisible"
      title="分配权限"
      width="30%"
    >
      <el-form :model="authObjectForm" label-position="top" label-width="80px">
        <el-form-item label="用户权限">
          <el-row :gutter="20">
            <el-col :span="23">
              <el-select
                v-model="authObjectForm.userIdList"
                class="width-full" multiple placeholder="请选择用户"
                @remove-tag="event=>{handleRemoveUserTag(event,'userList','id')}"
                @click.native="openChooseHandle('userChooseTable',selectedObj.userList)"
              >
                <el-option
                  v-for="item in selectedObj.userList"
                  :key="item.id"
                  :label="item.userName"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="角色">
          <el-row :gutter="20">
            <el-col :span="23">
              <el-select
                v-model="authObjectForm.roleIdList"
                class="width-full"
                multiple placeholder="请选择角色"
                @remove-tag="event=>{handleRemoveUserTag(event,'roleList','id')}"
                @click.native="openChooseHandle('roleChooseTable',selectedObj.roleList)"
              >
                <el-option
                  v-for="item in selectedObj.roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="部门">
          <el-row :gutter="20">
            <el-col :span="23">
              <el-select
                v-model="authObjectForm.deptIdList"
                class="width-full"
                multiple
                placeholder="请选择部门" @remove-tag="event=>{handleRemoveUserTag(event,'deptList','id')}"
                @click.native="openChooseHandle('deptChooseTree',selectedObj.deptList)"
              >
                <el-option
                  v-for="item in selectedObj.deptList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="authDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAuthHandle">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import authGroup from '../auth/group'
import {delAuthGroup, getAuthGroup, listAuthGroup, saveAuthObjs} from '@/api/project/publish'
import UserChooseTable from '@/views/system/user/chooseTable'
import RoleChooseTable from '@/views/system/role/chooseTable'
import DeptChooseTree from '@/views/system/dept/chooseTree'
import UrlOperate from "./UrlOperate"

export default {
  name: 'DesignatedPublish',
  components: {
    UrlOperate,
    DeptChooseTree,
    RoleChooseTable,
    UserChooseTable,
    authGroup
  },
  data() {
    return {
      createDataLink: '',
      formKey: '',
      authDialogVisible: false,
      authGroupList: [],
      // 选中对象 如用户角色 等
      selectedObj: {
        userList: [],
        roleList: [],
        deptList: []
      },
      // 授权问卷对象
      authObjectForm: {
        formKey: '',
        authGroupId: null,
        userIdList: [],
        roleIdList: [],
        deptIdList: []
      }
    }
  },
  created() {
    this.formKey = this.$route.query.key
    let url = window.location.protocol + '//' + window.location.host
    this.createDataLink = `${url}/d/${this.formKey}`
    this.queryAuthGroupListHandle()
  },
  methods: {
    queryAuthGroupListHandle() {
      // 查询
      listAuthGroup(this.formKey).then((res) => {
        this.authGroupList = res.data
      })
    },
    updateAuthGroupHandle(id) {
      getAuthGroup(id).then((res) => {
        this.$refs.authGroup.formAuthGroup = res.data
        this.$refs.authGroup.fieldCheckedHandle()
        this.$refs.authGroup.dialogVisible = true
        this.$refs.authGroup.dialogTitle = '修改权限组'
      })
    },
    copyAuthGroupHandle(id) {
      getAuthGroup(id).then((res) => {
        this.$refs.authGroup.formAuthGroup = res.data
        this.$refs.authGroup.formAuthGroup.id = null
        this.$refs.authGroup.fieldCheckedHandle()
        this.$refs.authGroup.dialogVisible = true
      })
    },
    // 提交授权组的授权对象
    submitAuthHandle() {
      saveAuthObjs(this.authObjectForm).then(() => {
        this.msgSuccess('保存成功')
        this.queryAuthGroupListHandle()
        this.authDialogVisible = false
      })
    },
    deleteAuthGroupHandle(id) {
      this.$confirm('此操作将永久删除该权限组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAuthGroup(id).then((res) => {
          this.queryAuthGroupListHandle()
          this.msgSuccess('删除成功')
        })
      }).catch(() => {

      })
    },
    // 分配权限组到用户
    authGroupToUserHandle(group) {
      // 修改时显示以保存的值
      if (group.authObjs) {
        this.selectedObj.userList = group.authObjs.userList
        this.selectedObj.roleList = group.authObjs.roleList
        this.selectedObj.deptList = group.authObjs.deptList
        // 把字符串数组转成int数组 不然select会无法选中
        let {userIdList, roleIdList, deptIdList, id} = group.authObjs.source
        this.authObjectForm.userIdList = userIdList && userIdList.map(Number)
        this.authObjectForm.roleIdList = roleIdList && roleIdList.map(Number)
        this.authObjectForm.deptIdList = deptIdList && deptIdList.map(Number)
        this.authObjectForm.id = id
      } else {
        this.selectedObj = {}
        this.authObjectForm = {}
      }
      this.authObjectForm.authGroupId = group.id
      this.authObjectForm.formKey = this.formKey
      this.authDialogVisible = true
    },
    crateAuthGroupHandle() {
      this.$refs.authGroup.clearFormAuthGroup()
      this.$refs.authGroup.dialogVisible = true
      this.$refs.authGroup.dialogTitle = '新增权限组'
    },
    handleRemoveUserTag(val, name, key) {
      this.selectedObj[name] = this.selectedObj[name].filter((item) => item[key] !== val)
    },
    // 打开选择窗口
    openChooseHandle(name, val) {
      this.$refs[name].showDialog(val)
    },
    // 选中数据事件
    submitChooseHandle(name, val) {
      this.$set(this.selectedObj, `${name}List`, val)
      this.$set(this.authObjectForm, `${name}IdList`, val.map((item) => item.id))
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-content {
  padding: 20px;
}

.auth-obj-tag {
  margin: 2px;
}
</style>
